from flask import *
import json
import os
import sys
import zipfile
import threading

sys.path.append('.')
base_dir = os.path.abspath('.')

from server.errors import *
from server.util import *
from server.database import FlashDatabase

db = FlashDatabase()
app = Flask(__name__)
# 管理进程用的线程池
threads = []


def run_command(command: str):
    os.system(command)


@app.route('/launch/<string:name>')
def launch(name: str):
    # 判断app是否存在并且已经配置
    app_info = db.get_app_info(name)
    if not os.path.exists('apps/%s' % name) \
            or not os.path.isdir('apps/%s' % name)\
            or app_info is None:
        return make_errors(FLASHSERVER_ERRORS['Deploy']['AppNotFoundError'])
    # 激活环境
    os.chdir(os.path.join(base_dir, 'apps/%s' % name))
    os.system('.\\Script\\activate')
    # 运行指令
    th = threading.Thread(target=run_command, args=(app_info['info']['command'], ))
    global threads
    th.setDaemon(True)
    th.start()
    threads.append(th)
    # os.system(app_info['info']['command'])
    # 退出
    # os.system('deactivate')
    return FLASHSERVER_ERRORS['General']['OK']


"""
:param ZIP file (form-data:file)
:method POST
"""


@app.route('/deploy', methods=['POST'])
def deploy():
    if 'file' not in request.files:
        return make_errors(FLASHSERVER_ERRORS['Deploy']['AppSettingsError'])
    file = request.files['file']
    try:
        zip_file = zipfile.ZipFile(file)
        # 先获取name
        config = json.loads(zip_file.read('flashserver.json'))
        name = config['info']['name']
        un_zip(zip_file, 'apps/%s' % name)
        result = db.set_app_new(config)
        if not result:
            return make_errors(FLASHSERVER_ERRORS['Deploy']['AppSettingsError'], data='flashserver.json文件错误')
    except Exception as e:
        return make_errors(FLASHSERVER_ERRORS['Deploy']['AppSettingsError'], data=str(e))
    # 判断app是否存在：是否找到配置信息
    app_info = db.get_app_info(name)
    if app_info is None:
        return make_errors(FLASHSERVER_ERRORS['Deploy']['AppNotFoundError'])

    # 切换工作目录
    os.chdir(os.path.join(base_dir, 'apps'))

    # 检测有没有配置过virtualenv
    if not os.path.exists(os.path.join(base_dir, 'apps/%s/pyvenv.cfg' % name)):
        # 配置virtualenv
        os.system('virtualenv %s' % name)
        # 激活环境
        os.system('.\\%s\\Scripts\\activate' % name)
        os.chdir('%s' % name)
        # 安装依赖
        for p in app_info['info']['version_info']['requirements']:
            os.system('pip install %s' % p)
        # 退出环境
        os.system('deactivate')
        os.chdir(base_dir)
    return make_errors(FLASHSERVER_ERRORS['General']['OK'])


if __name__ == '__main__':
    app.run('0.0.0.0', port=8083, debug=False)
